import { hapTasks, OhosHapContext, OhosPluginId } from '@ohos/hvigor-ohos-plugin';
import { hvigor, FileUtil, getNode } from '@ohos/hvigor'
import { readFileSync } from 'fs';
import { appTasks, OhosAppContext } from '@ohos/hvigor-ohos-plugin';
/*导入变量为config的对象，获取打包配置参数*/
import { config } from '../hvigorfileConfig'

/*通过当前目录的hvigorfile.ts获取节点*/
const rootNode = getNode(__filename);

/*通过key-value形式记录hap包名称，key=Module Target,value=hap的文件名*/
let hapNameMap = {}

/*记录product，打包输出时用于自定义hap包名称*/
let _productName = "def"

/*为节点添加一个afterNodeEvaluate hook 在hook中修改该目录下的build-profile.json5的内容并使能*/
rootNode.afterNodeEvaluate(node => {
  const path = require('path');
  const parentDir = path.dirname(path.dirname(__filename));

  /*通过项目根目录的hvigorfile.ts脚本文件路径获取对应的节点对象*/
  const appNode = getNode(path.join(parentDir, "hvigorfile.ts"))

  const appContext = appNode.getContext(OhosPluginId.OHOS_APP_PLUGIN) as OhosAppContext;
  const appJsonOpt = appContext.getAppJsonOpt();

  /*获取当前product，用于自定义hap文件名*/
  _productName = appContext.getCurrentProduct().getProductName() ?? ""

  /*获取此节点使用插件的上下文对象 此时为hap插件 获取hap插件上下文对象*/
  const hapContext = node.getContext(OhosPluginId.OHOS_HAP_PLUGIN) as OhosHapContext;

  /*通过上下文对象从entry目录build-profile.json5文件中读出来的obj对象*/
  const buildProfileOpt = hapContext.getBuildProfileOpt();
  const targets = buildProfileOpt['targets']

  /*获取编译时生成的时间，[在hvigorfileConfig.ts文件中的getLocalFileContent()方法中生成]*/
  /*因为工程根目录下hvigor先于module目录下hvigor执行，所以这里的buildTime直接通过变量config获取*/
  /*记得导入import { config } from '../hvigorfileConfig'*/
  let timeStr = config["buildTime"]

  /*因为工程根目录下hvigor先于module目录下hvigor执行，同理可得：此时获取的versionCode是被动态修改之后的值*/
  let versionCode = appJsonOpt["app"]["versionCode"]

  /*遍历build-profile.json5中targets节点下的内容*/
  for (let i = 0; i < targets.length; i++) {
    let output = targets[i]["output"]
    if (output && output["artifactName"]) {
      /*获取target name，自定义hap名称需要*/
      let tempName = targets[i]["name"]
      if (tempName) {

        /*设置自定义hap名称，版本号+自定义名+product+target+打包时间.hap*/
        const resultName =output["artifactName"] = versionCode + "Harmony" + "_"+ _productName + "_" + tempName + "_" + timeStr

        /*key-value形式保存hap文件名，key=target name*/
        hapNameMap[tempName] = resultName + ".hap"
        // console.info("===========" + resultName)
      }
    }
  }
  //console.info("===hapNameMap========" + JSON.stringify(hapNameMap))
  /*将buildProfileOpt对象设置回上下文对象以使能到构建的过程与结果中*/
  hapContext.setBuildProfileOpt(buildProfileOpt);
})


/*添加一个构建结束的回调函数(打包完成后，复制hap文件到新目录)*/
hvigor.buildFinished(buildResult => {

  const hapContext = rootNode.getContext(OhosPluginId.OHOS_HAP_PLUGIN) as OhosHapContext;
  hapContext?.targets((target: Target) => {
    /*通过target name获取对应的hap文件*/
    let hapName = hapNameMap[target.getTargetName()]

    //console.info(target.getTargetName()+"======target=====" +hapName)
    if (!hapName) {
      return
    }
    const path = require('path');

    /*获取编译完成后的hap包所在路径*/
    const dirPath = target.getBuildTargetOutputPath();

    /*得到hap包完整路径*/
    let hapPath = path.join(dirPath, hapName)
    //console.info("======hapPath=====" +hapPath)
    if (FileUtil.exist(hapPath)) {
      /*复制到目标目录*/
      const parentPath = path.join(path.dirname(path.dirname(__filename)), "_hap")

      /*如果目标目录不存在就创建*/
      FileUtil.ensureDirSync(parentPath)

      /*定义目标文件路径*/
      const destPath = path.join(parentPath, hapName)

      /*复制hap文件到目标路径*/
      FileUtil.copyFileSync(hapPath, destPath)
    }

  })
})


export default {
  system: hapTasks, /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins: []         /* Custom plugin to extend the functionality of Hvigor. */
}
